package com.test.transaction.controller;

import com.test.transaction.service.LogService;
import com.test.transaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/u")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Transactional
    @RequestMapping("/A")
    public String A(String username, String password) {
        // 向用户表插入一条用户信息
        userService.register(username, password);
        // 记录对用户表的操作日志
        logService.logUser(username,username + " 用户注册成功");
        return "注册成功";
    }


    @RequestMapping("/u1")
    public String test2(String username, String password) {
        userService.register(username, password);
        try {
            // 抛出算术异常
            int a = 0/0;
        }catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return "注册成功";
    }

    // 只要属于 Exception 的异常，就会触发回滚操作
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/t1")
    public String test1(String username, String password) throws IOException {
        userService.register(username, password);
        if (true) {
            throw new IOException();
        }
        return "注册成功";
    }
}
